<?php
/**
 * Created by PhpStorm
 *
 * Date: 2023/3/9
 * Time:9:49
 */

namespace app\api\controller;



use app\common\controller\Api;
use app\common\model\User;
use app\common\utils\WechatUtil;
use fast\Random;
use think\Config;

/**
 * 微信小程序授权登录
 */
class Weixin extends Api
{
    protected $noNeedLogin = ['getOpenId','schoolList'];
    protected $noNeedRight = ["*"];


    protected $keeptime = 259200000; //30天

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 测试
     * @APiInternal()
     */
    public function test()
    {
        $code = "0134vt0w33gMd03aUL0w3GvmeO34vt0L";
        $wechat = new WechatUtil();
        $data = $wechat->getOpenid($code);

    }





    /**
     * 授权登录 获取openid
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="string", required=true, description="code")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="avatar", type="string", required=true, description="头像")
     */
    public function getOpenId()
    {
        if (request()->isPost()) {
            $code = $this->request->post("code");
            $nickname = $this->request->post("nickname");

            if (empty($code)) {
                $this->error("code必传");
            }
            $wechat = new WechatUtil();
            $data = $wechat->getOpenid($code);
            if (!isset($data['errcode'])) {
                $openid = $data['openid'];
                $unionid = $data['unionid']??"";
                $model_user = new User();
                $info = $model_user
                    ->where(['openid' => $openid])
                    ->find();
                $avatar = Config::get("site.default_image");
                if (!$info) {
                    $params = [
                        'nickname' => $nickname,
                        'avatar' => $avatar,
                        'openid' => $openid,
                        'unionid' => $unionid,
                        'money' => 1,
                    ];
                    $ret = $this->auth->register($nickname, Random::alnum(), '', '', $params);
                } else {
                    if ($nickname){
                        $info->nickname = $nickname;
                    }
//                    if ($avatar){
//                        $info->avatar = $avatar;
//                    }

                    $info->save();
                    $ret = $this->auth->direct($info->id);
                }
                if ($ret) {
                    $data = ['userinfo' => $this->auth->getUserinfo()];
                    $this->success(__('Logged in successful'), $data);
                } else {
                    $this->error($this->auth->getError());
                }
            }
            $this->error("解析有误");
        }
        $this->error('请求方法不正确！');
    }


    /**
     * 获取手机号
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="string", required=true, description="code")
     */
    public function getPhone()
    {
        if ($this->request->isPost()) {
            $code = $this->request->post("code");
            $wechat = new WechatUtil();
            $data = $wechat->getPhoneNumber($code);
            if ($data['errcode'] == 0) {
                $this->auth->getUser()->save(['mobile' => $data['phone_info']['phoneNumber']]);
                $this->success("手机号绑定成功",$data['phone_info']['phoneNumber']);
            }
            $this->error("手机号解析出错");
        }
    }

    protected function doCurl($url)
    {
        $curl = curl_init();
        // 使用curl_setopt()设置要获取的URL地址
        curl_setopt($curl, CURLOPT_URL, $url);
        // 设置是否输出header
        curl_setopt($curl, CURLOPT_HEADER, false);
        // 设置是否输出结果
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 设置是否检查服务器端的证书
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // 使用curl_exec()将CURL返回的结果转换成正常数据并保存到一个变量
        $data = curl_exec($curl);
        // 使用 curl_close() 关闭CURL会话
        curl_close($curl);
        return json_decode($data);
    }


}